package noema.processManagement.ghostProcess;

import java.util.Date;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.drools.runtime.StatefulKnowledgeSession;
import org.jbpm.process.audit.NodeInstanceLog;
import org.jbpm.process.instance.ProcessInstance;

import noema.bam.InstanceMonitoring;
import noema.dataModel.ForcedAction;
import noema.dataModel.Patient;
import noema.interceptor.LoggerInterceptor;
import noema.session.SessionFactory;

@Stateless
@Interceptors(LoggerInterceptor.class)
public class GhostProcessManagementImpl implements GhostProcessManagement {

	@PersistenceContext(unitName = "application.data")
	private EntityManager em;
	@EJB
	private SessionFactory sessionFactory;
	@EJB
	private InstanceMonitoring bam;

	@Override
	public void forceAction(Patient p, String pathway, String why, String what,
			String who) {
		p = em.find(Patient.class, p.getHealthCardId());
		if (p == null) {
			throw new IllegalArgumentException(p+" not exists");
		}
		StatefulKnowledgeSession ksession = sessionFactory.getSession(p);
		for (Object obj : ksession.getProcessInstances()) {
			ProcessInstance instance = (ProcessInstance) obj;
			if (instance.getProcessId().equals(pathway)) {
				instance.setState(ProcessInstance.STATE_SUSPENDED);
				ForcedAction action = new ForcedAction();
				action.setDate(new Date());
				NodeInstanceLog node=bam.getActualNodeOfInstance(instance.getId());
				action.setNodeId(node.getNodeId());
				action.setNodeName(node.getNodeName());
				action.setPathwayId(pathway);
				action.setPatient(p);
				action.setWhat(what);
				action.setWho(who);
				action.setWhy(why);
				em.persist(action);
				break;
			}
		}
	}

	@Override
	public void resumePathway(Patient p, String pathway) {
		p = em.find(Patient.class, p.getHealthCardId());
		if (p == null) {
			throw new IllegalArgumentException(p+" not exists");
		}
		StatefulKnowledgeSession ksession = sessionFactory.getSession(p);
		for (Object obj : ksession.getProcessInstances()) {
			ProcessInstance instance = (ProcessInstance) obj;
			if (instance.getProcessId().equals(pathway)) {
				instance.setState(ProcessInstance.STATE_ACTIVE);
				break;
			}
		}
	}

}
